import json

from client.redis_client import r
from client import es_client


async def move_trajectory_to_es(imei: str):
    es = await es_client.get_es_client()
    list_from_redis = r.lrange('location_' + imei, 0, -1)
    trajectory = []
    source = json.loads(r.hget('state_' + imei, 'source'))
    if len(list_from_redis) > 0:
        for location_str in list_from_redis:
            location = json.loads(location_str)
            trajectory.append({
                    "fix": "WIFI",
                    "lon": str(location['lon']),
                    "fixedPosition": 1,
                    "ctm": location['ctm'],
                    "lat": str(location['lat'])
                })
        trajectory_data = {
            "dt": source['dt'],
            "dataAuthority": source['dataAuthority'],
            "imei": imei,
            "trajectory": trajectory
        }
        await es.index_document('p_trajectory_record', trajectory_data)
        r.delete('location_' + imei)

